import 'package:enterprise_v8/app/components/toast_widget.dart';
import 'package:enterprise_v8/app/components/update_dialog.dart';
import 'package:enterprise_v8/app/core/core.dart';
import 'package:enterprise_v8/app/core/http/http.dart';
import 'package:enterprise_v8/app/core/utils/interface.dart';
import 'package:enterprise_v8/app/data/entities/auth/app_update_entity.dart';
import 'package:enterprise_v8/global.dart';

/// @Author: zxh
/// @Date: 2024/2/28 16:23
/// @LastEditTime: 2024/2/28 16:23
/// 版本更新相关工具类
class UpdateUtil {
  /// 检查更新 判断应用是否有升级
  /// [isShowToast] 是否显示toast
  static void checkUpdate({bool isShowToast = false}) async {
    /// todo 等待企业接口
    final res = await HttpUtil().generateGetRequest<AppUpdateEntity>(Interface.appUpdateUrl, queryParameters: {'type': 2, 'serverType': 'meifeng'}).execute(
      isShowLoading: true,
      showText: '检查中...',
    );
    res.onSuccess((value) {
      if (value.data != null) {
        if (isUpdateVersion(value.data!.version, Global.packageInfo.version)) {
          // 有升级
          showDialog(
            barrierDismissible: false,
            context: Get.context!,
            builder: (context) {
              return PopScope(
                canPop: false,
                child: UpdateDialog(
                  downloadAddress: value.data!.downloadAddress,
                  isForce: value.data!.isForcedUpgrade == 1,
                  upDateContent: value.data!.upgradeDescription,
                  version: value.data!.version,
                ),
              );
            },
          );
        } else {
          if (isShowToast) {
            AppToast.showSuccess('当前版本已是最新版本');
          }
        }
      }
    });
  }

  /// 判断当前版本号和后台版本号是否一致
  /// [newVersion] 后台版本号
  /// [old] 当前版本号
  /// return true 需要升级 false 不需要升级
  static bool isUpdateVersion(String? newVersion, String? old) {
    if (newVersion == null || newVersion.isEmpty || old == null || old.isEmpty) {
      return false;
    }
    int newVersionInt, oldVersion;
    final newList = newVersion.split('.');
    final oldList = old.split('.');
    if (newList.isEmpty || oldList.isEmpty) {
      return false;
    }
    for (int i = 0; i < newList.length; i++) {
      newVersionInt = int.parse(newList[i]);
      oldVersion = int.parse(oldList[i]);
      if (newVersionInt > oldVersion) {
        return true;
      } else if (newVersionInt < oldVersion) {
        return false;
      }
    }
    return false;
  }
}
